﻿

function JsonStringToDate(str) {
    try{
        var re = /-?\d+/;
        var m = re.exec(str); 
        return new Date(parseInt(m[0]));
    }catch(e){
        return new Date(1970,1,1);
    }
}

Date.prototype.format = function (format) //author: meizz
{
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}

//form表单获取为JSON对象
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

// 时间戳转字符串 按【2012-02-13 09:09:09】的格式返回日期
function dateformatTime( val,formatstr) {
    try {
        var timestr=0;
        val =''+val;
        if(  val.length==10){
            timestr=parseInt(val)*1000;
        }else if(  val.length>=13){
            timestr=parseInt(val) ;
        }
        else{
            timestr=0;
        }
        if(timestr!=0) {
            var date = new Date(timestr);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            return date.format(formatstr);
        }
        else {
            return val;
        }
    } catch (e) {
        return val ;
    }
}

function formatTime(val){
    return dateformatTime( val,"yyyy-MM-dd hh:mm:ss");
}
function formatDate(val) {
    return dateformatTime( val,"yyyy-MM-dd");
}

//获取URL对应
function getQueryStringByName(name) {
    var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[0].replace(name + '=', '').replace('?', '').replace('&', '');
}

function formatter_IsNo(value, rec) { 
    return (value == null || value.trim() == '0') ? '<span style="color:Red">否</span>' : '<span style="color:#216499">是</span>';
}

 

function formatter_RMB(value, rec) {
    return '<span style="color:#216499">' + value/100 + '元</span>';
}


function formatter_Sex(value, rec) {
    if (value == '0') {
        return '女';
    }
    else if (value == '1') {
        return '男';
    }
    else {
        return '未知';
    }
}
 
//保留对应位数
function MarkPrecision(value, Precision) {
    return parseInt(value * Precision) / Precision;
}

//利用匿名函数将脚本包裹起来
(function(){
//自定义命名空间v
var onluy={ };
onluy.secretkey='e036hlqtculakx38tjw2u9gs';
onluy.basePath =function(){
	return  $('#basePath').val();
}
 
//=========================DES====================
onluy.DES={}
//封包加解密 
onluy.DES.encrypt=function(message,key) {   
	var keyHex = CryptoJS.enc.Utf8.parse(key);  
	var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	}); 
	return encrypted.toString();
} 

onluy.DES.decrypt=function(ciphertext,key) { 
	var keyHex = CryptoJS.enc.Utf8.parse(key); 
	var decrypted = CryptoJS.DES.decrypt({
		ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
	}, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	}); 
	return decrypted.toString(CryptoJS.enc.Utf8);
}

//=========================ajax====================
onluy.ajax={}

onluy.ajax.basePath='http://10.125.128.29:9035';
//构造加密数据的封包
onluy.ajax.makeParam=function(param,key)
{ 
	var message=''; 
	if (typeof (param) != undefined && typeof (param) == 'object') { 
		message=JSON.stringify(param);
	}
	else{
		message= param; 
	} 
	var enResult = onluy.DES.encrypt (message,key);//加密   
	var obj={
	  "reqParam":enResult, 
	  "sys":"onluy"
	}
	return obj;
}

onluy.ajax.checklogin=function( ) {
    var login_userinfo_str=$.cookie('login_userinfo');
    console.log("==============login_userinfo_str" + login_userinfo_str);
    var login_userinfo = JSON.parse(login_userinfo_str) ;
    if (login_userinfo == null || login_userinfo['staffId'] == null){
        window.top.location.href= "/login";
        return false;
    }

    return true;
}


onluy.ajax.getData=function(strUrl,param,key,success,error ) {
    if (false == onluy.ajax.checklogin()) return;//校验登录信息

    $.ajax({
        async: true,
        cache: false,
        type: "post",
        url: Onluy.ajax.basePath + strUrl,
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(param),//onluy.ajax.makeParam(param,key),
        dataType: 'json',
        error: function (rq, textStatus, errorThrown) {
            //var errmsg={success:false,msg:rq.responseText,state:textStatus};
            error(rq.responseText + "<br/>" + textStatus + "<br/>" + errorThrown);
        },
        success: function (result) {
            var resobj = {};
            // if(result.respInfo){
            // 	resobj=onluy.DES.decrypt (result.respInfo,key);
            // 	resobj=JSON.parse(resobj);
            // }
            // else{
            resobj = result;
            //}
            //alert(JSON.stringify(resobj));
            success(resobj);
        }
    });
}

onluy.ajax.getSimpData=function(url, param,success,error){
        onluy.ajax.getData( url,param,onluy.secretkey, success,error );
        return true;
}

onluy.ajax.postData=function(strUrl,param,success,error ) {
    if (false == onluy.ajax.checklogin()) return;//校验登录信息

    console.log('postData param  :' + JSON.stringify(param));
    $.ajax({
        async: false,
        cache: false,
        type: "post",
        url: Onluy.ajax.basePath + strUrl,
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(param),
        dataType: 'json',
        error: function (rq, textStatus, errorThrown) {
            //var errmsg={success:false,msg:rq.responseText,state:textStatus};
            error(rq.responseText + "<br/>" + textStatus + "<br/>" + errorThrown);
        },
        success: function (result) {
            console.log('postData success result :' + JSON.stringify(result));
            success(result);
        }
    });
}

onluy.easyui={    
    title: " ",
    idField: "编码字段", 
    titleField: "标题字段",
    toolbar: 'Toolbar', 
	postAction: 'add',
	url: '-', 
	editor:{
	    title: "弹出框名称",
		winid:'',
		formid:'EditForm',
		width:720,
		height:300
	},
	toolbar: 'App_Type_Toolbar',
	datagrid: 'App_Type_Grid',
	selRow:{},
	model: {}   

} ;



onluy.easyui.ShowException= function(data) { 
	var msg ='';
	if (typeof (data) != undefined && typeof (data) == 'object') { 
		if(data.success){
			msg=data.msg;
		}
		else{
			msg=JSON.stringify(data);
		} 
	}
	else{
		msg=data;
	}
	
    $('#PopWindowContet').html("异常信息："+msg);
    $('#PopWindow').window({
        width: 400,
        height: 100,
        collapsible:false,
        minimizable:false,
        maximizable:false,
        title:'异常',
        modal: true
    });
    $('#PopWindow').window('open');
}
onluy.easyui.ShowMsg= function(title,msg) {
	$.messager.alert(title, msg);
}
 
 
/*======================loder===============================*/
onluy.easyui.Loader=function( param,success,error){
    console.log("===========Loader param"+JSON.stringify(qureparam))
	var opts ={};
	if (!opts.url)try{ 
		opts =$(this).datagrid('options'); 
	} catch(e){ }
	
	if (!opts.url)try{ 
		opts =$(this).treegrid('options');  
	} catch(ex){  }
	
	if (!opts.url)try{ 
		opts =$(this).combobox('options');   
	} catch(ex){ }
	
    if (  !opts.url) {
		alert('Loader 异常！' );
        return false;
    }

    var qureparam={
        "reqBody": {
            //"parentMenuCode": "SYS"
        },
        "reqHead": {
            "currPage": param.page,
            "pageSize": param.rows
        }
    };

    if(param.value!=null && param.value!=""){
        qureparam.reqBody[param.name]=param.value;
    }

    for(p in param){
        if('rows'==p)continue;
        if('page'==p)continue;
        if('value'==p)continue;
        if('name'==p)continue;
        qureparam.reqBody[p]=param[p];
    }



    console.log("===========Loader qureparam"+JSON.stringify(qureparam))
    onluy.ajax.getData(opts.url,qureparam,onluy.secretkey, function (data) {
        if(data.rspCode !=0) {
            $.messager.alert('获取数据异常', data.rspDesc );
            return;
        }
        var repdata={
            success :	true ,
            msg: data.rspDesc,
            msgtype:"",
            total:0,
            rows:[]
        }
        if(data.rspData && data.rspData.list){
            repdata.total=data.rspData.total;
            repdata.rows=data.rspData.list;
        }
        success(repdata);
    },error );
    return true;
}

onluy.easyui.treeLoader=function( param,success,error){ 
	var opts = $(this).tree('options'); 
    if (!opts.url) {
        return false;
    }  

    var data ;
    if(!param.id && opts.data){
    	data =opts.data;
    }
    else{
    	data=param;
    } 
    //alert(JSON.stringify(data));
    onluy.ajax.getData(opts.url,data,onluy.secretkey, success,error ); 
    return true;
}

/*================loadfilter=================================*/
onluy.easyui.loadfilter= function(data){ 
    	var i=0; 
    	for(i=0;i<data.length;i++){ 
    		var temp=data[i];
    		data[i].id=temp[onluy.easyui.idfield]; 
    		data[i].text=temp[onluy.easyui.titlefield] ; 
    		if(data[i].childCount && data[i].childCount>0){
        		data[i].state="closed"  ; 
    		}else{
        		data[i].state="open"  ;
    		}
        }
        return data;    
}
 
onluy.easyui.FindRowById=function(id) {
     return null;
}

onluy.easyui.ShowEditForm=function(id) {   
}


//方便扩展

onluy.easyui.submit =function() {
	var validate=$("#"+onluy.easyui.editor.formid).form('validate');
	var url = onluy.easyui.url+'/'+onluy.easyui.postAction ;
	var formdata =$("#"+onluy.easyui.editor.formid).serializeObject();
	var postdata={
        "reqBody": {} ,
        "reqHead": {
            "sysCode": "contest18_test"
        }
    }
    postdata.reqBody=formdata;
    console.log("submit data : "+ JSON.stringify(postdata))
	if(validate){ 
		Onluy.ajax.getData(url,postdata,Onluy.secretkey, function(result){
             //{"rspCode":0,"rspDesc":"修改成功！","rspData":null}
            var success=(result.rspCode == 0);
			 onluy.easyui.ShowMsg(success ? "提示" : "错误",result.rspDesc);
	         if (success) {
	        	 onluy.easyui.reload();
	         }
		},function(error){
			onluy.easyui.ShowException(error);
		} ); 
	} 
	else
	{
		onluy.easyui.ShowMsg( "提示"  ,"请认真填写必填选项！");
	} 
}

//方便扩展
onluy.easyui.griddelrow =function(id) {
}



onluy.easyui.Init=function(){ 
	 
	
	
}
 

////////////////////////////////////////////////////////////
//定义全局变量命令空间
window.Onluy = onluy;

window.TradeModel =onluy.easyui;
////////////////////////////////////////////////////////////
})();
